package com.wangxiaonan.wxwork.controller;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Agent;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.AgentService;
import com.wangxiaonan.wxwork.service.MessageService;
import com.wangxiaonan.wxwork.service.TokenService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author: wangxiaonan
 * @Date: 2018/8/23
 **/
@RestController
@RequestMapping("/message")
public class MessageController {
    private static final String AGENT_TOKEN_KEY = "agent_";

    @Resource
    private AgentService agentService;
    @Resource
    private TokenService tokenService;
    @Resource
    private MessageService messageService;

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String sendMessage(@RequestParam(value = "agent_id") String agentId, @RequestBody String msgBody) {
        JSONObject rs = new JSONObject();
        rs.put("status","ok");
        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            rs.put("status", "agent_not_exists");
            return rs.toJSONString();
        }
        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException e) {
            rs.put("msg", e.getMsg());
            rs.put("status", e.getCode());
            return rs.toJSONString();
        }

        try {
            JSONObject jsonObject = messageService.sendMessage(token, msgBody);
            if ("0".equals(jsonObject.getString("errcode"))) {
                rs.put("data",jsonObject);
            } else {
                rs.put("status", "retry");
            }
        } catch (Exception e){
            rs.put("status", "send_fail");
            return rs.toJSONString();
        }

        return rs.toJSONString();
    }

}
